package com.wie.staffhubpro.controller;

import com.wie.staffhubpro.domain.dto.LoginDTO;
import com.wie.staffhubpro.domain.entity.LoginLog;
import com.wie.staffhubpro.domain.entity.Result;
import com.wie.staffhubpro.domain.entity.Role;
import com.wie.staffhubpro.domain.entity.User;
import com.wie.staffhubpro.domain.vo.LoginVO;
import com.wie.staffhubpro.properties.JwtProperties;
import com.wie.staffhubpro.service.IpUtils;
import com.wie.staffhubpro.service.LoginLogService;
import com.wie.staffhubpro.service.RoleService;
import com.wie.staffhubpro.service.UserService;
import com.wie.staffhubpro.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.AccountNotFoundException;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private LoginLogService loginLogService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户登录
     */
    @PostMapping
    public Result login(@RequestBody LoginDTO loginDTO, HttpServletRequest request) throws AccountNotFoundException {
        log.info("密码登录：{}", loginDTO.getUsername());
        // 计入登录日志
        LoginLog loginLog = new LoginLog().builder()
                .ip(IpUtils.getClientIp(request))
                .username(loginDTO.getUsername())
                .loginTime(LocalDateTime.now())
                .build();
        loginLogService.save(loginLog);
        // 校验用户
        User user = userService.login(loginDTO);
        // 获取用户的角色名称
        Role role = roleService.getById(user.getRoleId());
        // 登录成功，生成令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getSignKey(),
                jwtProperties.getExpire(),
                claims);
        LoginVO loginVO = new LoginVO().builder()
                .token(token)
                .roleId(user.getRoleId())
                .roleName(role.getRoleName())
                .build();
        return Result.success(loginVO);
    }

}
